package com.jingdianjichi.oss.util;

import com.jingdianjichi.oss.entity.FileInfo;
import io.minio.*;
import io.minio.messages.Bucket;
import io.minio.messages.Item;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.InputStream;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * minio文件操作工具
 */
@Component
public class MinioUtil {

    @Resource
    private MinioClient minioClient;

    /**
     * 创建bucket桶
     */
    public void createBucket(String bucketName) throws Exception{
        boolean exists = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
        if(!exists){
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
        }
    }

    /**
     * 上传文件
     * @param inputStream
     * @param bucketName
     * @param objectName
     * @throws Exception
     */
    public void uploadFile(InputStream inputStream,String bucketName,String objectName) throws Exception{
        //stream参数解释未inputstream为要传入的文件输入流，objectsize表示传入文件大小，-1表示未知，max表示文件分块最大大小，
        //大文件超过阈值,会自动分块上传
        minioClient.putObject(PutObjectArgs.builder().bucket(bucketName)
                .stream(inputStream,-1,Integer.MAX_VALUE).build());
    }

    /**
     * 列出所有桶
     * @return
     * @throws Exception
     */
    public List<String> getAllBucket()throws Exception{
        List<Bucket> buckets = minioClient.listBuckets();
        return buckets.stream().map(Bucket::name).collect(Collectors.toList());
    }

    /**
     * 列出所有桶及文件
     * @return
     * @throws Exception
     */
    public List<FileInfo> getAllFile(String bucketName)throws Exception{
        Iterable<Result<Item>> results = minioClient.listObjects(ListObjectsArgs.builder().bucket(bucketName).build());
        List<FileInfo> fileInfoList=new LinkedList<>();
        for (Result<Item> result : results) {
            FileInfo fileInfo=new FileInfo();
            Item item= result.get();
            fileInfo.setFileName(item.objectName());
            fileInfo.setDirectoryFlag(item.isDir());
            fileInfo.setEtag(item.etag());
            fileInfoList.add(fileInfo);
        }
        return fileInfoList;
    }

    /**
     * 下载文件
     */
    public InputStream downLoad(String bucketName,String objectName) throws Exception{
        return minioClient.getObject(GetObjectArgs.builder().bucket(bucketName).object(objectName).build());
    }

    /**
     * 删除桶
     */
    public void  deleteBucket(String bucketName) throws Exception{
        minioClient.removeBucket(RemoveBucketArgs.builder().bucket(bucketName).build());
    }

    /**
     * 删除文件
     */
    public void deleteFile(String bucketName,String objectName) throws Exception{
        minioClient.removeObject(RemoveObjectArgs.builder().bucket(bucketName).object(objectName).build());
    }
}
